﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Linq;
using NHibernate;

namespace Scala.Data.Impl.Repo
{
    public abstract class BaseRepo<TEntity, TId> : IRepo<TEntity, TId> where TEntity : IEntity<TId>
    {
        protected readonly ISessionProvider sessionProvider;

        public BaseRepo(ISessionProvider sessionProvider)
        {
            if (sessionProvider == null) throw new ArgumentNullException("sessionProvider");
            this.sessionProvider = sessionProvider;     
        }

        protected virtual ISession Session
        {
            get { return sessionProvider.CurrentSession; }
        }

        #region IRepo<TEntity,TId> Members

        public void Save(TEntity entity)
        {
            Session.SaveOrUpdate(entity);
        }

        public void Remove(TEntity entity)
        {
            Session.Delete(entity);
        }

        public TEntity Get(TId id)
        {
            return Session.Get<TEntity>(id);
        }

        public TEntity Find(Func<TEntity, bool> funct)
        {
            return Session.Query<TEntity>().SingleOrDefault(funct);
        }

        public IEnumerable<TEntity> FindRange(Func<TEntity, bool> funct)
        {
            return Session.Query<TEntity>().Where(funct).ToList();
        }

        #endregion
    }
}
